/**
 * 
 * @author maxd
 * @date 2019.8.1
 */
import cnodeModel from '@/api/api.js';
// #ifdef H5
import wechat from '@/components/jweixin-module/wechat'
// #endif
module.exports = {

	logout() {
		this.remove("token");
		this.remove("isRealName");
	},
	loginClear() {
		this.remove("token");

	},
	showLoading(title) {
		uni.showLoading({
			title: title
		});
	},
	remove(value) {
		uni.removeStorageSync(value)
	},
	showToast(title, duration = 1500, mask = false, icon = 'none') {
		//统一提示方便全局修改
		if (Boolean(title) === false) {
			return;
		}
		uni.showToast({
			title,
			duration,
			mask,
			icon
		});
	},
	setJson: function(key, value) {
		let jsonString = JSON.stringify(value);
		try {
			uni.setStorageSync(key, jsonString);
		} catch (e) {
			// error
		}
	},
	setData: function(key, value) {
		try {
			uni.setStorageSync(key, value);
		} catch (e) {
			// error
		}
	},
	getData: function(key) {
		try {
			const value = uni.getStorageSync(key);
			if (value) {
				return value;
			}
		} catch (e) {
			// error
		}

	},
	getJson: function(key) {
		try {
			const value = uni.getStorageSync(key);
			if (value) {
				return JSON.parse(value);
			}
		} catch (e) {
			// error
		}

	},
	clear: function() {
		uni.clearStorage();
	},
	// 判断值是否为空
	isEmpty(obj) {
		try {
			if (obj == null || obj == undefined) {
				return true;
			}
			//判断数字是否是NaN
			if (typeof obj === "number") {
				if (isNaN(obj)) {
					return true;
				} else {
					return false;
				}
			}
			//判断参数是否是布尔、函数、日期、正则，是则返回false
			if (typeof obj === "boolean" || typeof obj === "function" || obj instanceof Date ||
				obj instanceof RegExp) {
				return false;
			}
			//判断参数是否是字符串，去空，如果长度为0则返回true
			if (typeof obj === "string") {
				if (obj.trim().length == 0) {
					return true;
				} else {
					return false;
				}
			}

			if (typeof obj === 'object') {
				//判断参数是否是数组，数组为空则返回true
				if (obj instanceof Array) {
					if (obj.length == 0) {
						return true;
					} else {
						return false;
					}
				}

				//判断参数是否是对象，判断是否是空对象，是则返回true
				if (obj instanceof Object) {
					//判断对象属性个数
					if (Object.getOwnPropertyNames(obj).length == 0) {
						return true;
					} else {
						return false;
					}
				}
			}
		} catch (e) {
			console.log(e);
			return false;
		}
	},
	// 判断是否实名 、登录
	async validate_realName_login() {
		var data = {
			realName: false,
			login: false
		}
		if (uni.getStorageSync('token') != undefined && uni.getStorageSync('token') != '') {
			data.login = true
			var res = await cnodeModel.getRealNameInfo()
			if (res.data.idCard == '' || res.data.name == '') {
				data.realName = false
			} else {
				data.realName = true
			}
		}
		return data
	},
	// 计算已售数量
	soldQuantity(num) {
		if (num >= 10000 && num != '') {
			// num = Number((num / 10000).toString().match(/^\d+(?:\.\d{0,1})?/)) + '万+'
			num = (num / 10000).toString().match(/^\d+(?:\.\d{0,1})?/) + '万+'
		}
		return num
	},
	// 封装用户是否授权定位
	authorizedLocation() {
		return new Promise((resolve, reject) => {
			uni.getSetting({
				success: (res) => {
					console.log(res)
					// res.authSetting['scope.userLocation'] === undefined  表示 初始化进入，从未授权
					// res.authSetting['scope.userLocation'] === true       表示 已授权
					// res.authSetting['scope.userLocation'] === false      表示 授权拒绝
					if (res.authSetting['scope.userLocation'] === undefined) {
						uni.authorize({
							scope: "scope.userLocation",
							success: () => {
								resolve(res.authSetting)
							},
							fail: () => {
								uni.showModal({
									title: "您未开启地理位置授权",
									content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
									success: (res) => {
										if (res.confirm) {
											uni.openSetting();
											// reject(res.authSetting)
										} else {
											reject(res.authSetting)
										}
									},
								});
							},
						});

					} else if (res.authSetting['scope.userLocation'] === true) {
						resolve(res.authSetting)
					} else if (res.authSetting['scope.userLocation'] === false) {
						uni.showModal({
							title: "您未开启地理位置授权",
							content: "请在系统设置中打开位置授权，以便我们为您提供更好的服务",
							success: (res) => {
								if (res.confirm) {
									uni.openSetting();
								} else {
									reject(res.authSetting)
								}
							},
						});
						// reject(res.authSetting)
					}
				}
			})
		})
	},
	payOrderFunc(resPay) {
		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN
			uni.requestPayment({
				'timeStamp': resPay.timeStamp,
				'nonceStr': resPay.nonceStr,
				'package': resPay.wxPackage,
				'signType': resPay.signType, //MD5
				'paySign': resPay.paySign,
				'success': function(res) {
					if (res.errMsg == 'requestPayment:ok') {
						uni.showToast({
							title: '支付成功',
						})
						resolve(res.authSetting)
					} else {
						reject(res.authSetting)
					}
				},
				'fail': error => {
					reject(error)
				},
				'complete': function(res) {

				}
			})
			// #endif

			// #ifdef H5
			wechat.wexinPay(resPay, function(callback) {
				resolve(callback)
			}, function(errorCallback) {
				reject(errorCallback)
			})
			// #endif

		})
	},

	repairRichText(html) {
		// 去掉<img>中style /width / height属性
		let newContent = html.replace(/<img[^>]*>/gi, (match) => {
			match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '')
			match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '')
			match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '')
			match = match.replace(/style\s*=\s*(["'])(?:(?!\1).)*\1/gi, '') // 去除 style=""这样的属性
			return match
		})
		// 修改所有style里的width属性为max-width:100%
		newContent = newContent.replace(/style="[^"]+"/gi, (match) => {
			match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi,
				'max-width:100%;')
			return match
		})

		// 去掉所有<br/>标签
		newContent = newContent.replace(/<br[^>]*\/>/gi, '')
		// img标签添加style属性：max-width:100%;height:auto
		newContent = newContent.replace(/\<img/gi,
			'<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"'
		)
		return newContent;
	},
	// 获取code
	getWxCode() {
		return new Promise((resolve, reject) => {
			uni.login({
				success: function(res) {
					if (res.code) {
						resolve(res.code)
					} else {
						reject(res.errMsg)
					}
				}
			})
		})
	},
	// 封装获取定位
	getLocation() {
		// #ifdef H5
		return new Promise((resolve, reject) => {
			wechat.scanQRJssdk(wx => {
				wx.getLocation({
					type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
					success: function(res) {
						// 成功
						resolve(res)
					},
					fail: function(err) {
						// 失败
						reject(err)
					},
					cancel: function(err) {
						// 取消
						reject(err)
					},
				});
			}, error => {
				reject()
			})
		})
		// #endif
		// #ifdef MP-WEIXIN
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'gcj02', //返回可以用于uni.openLocation的经纬度
				success: function(res) {
					resolve(res)
				},
				fail(err) {
					reject(err)
				}
			});
		})
		// #endif
	},
	// 封装定位导航
	openLocation(obj) {
		// #ifdef H5
		if (wechat.isWechat()) {
			wechat.scanQRJssdk(wx => {
				wx.openLocation({
					latitude: obj.latitude, // 纬度，浮点数，范围为90 ~ -90
					longitude: obj.longitude, // 经度，浮点数，范围为180 ~ -180。
					name: obj.name, // 位置名
					address: obj.address, // 地址详情说明
					scale: 20, // 地图缩放级别,整型值,范围从1~28。默认为最大
				});
			})
		} else {
			uni.showToast({
				title: '请在微信客户端中使用',
				icon: 'none'
			})
		}
		// #endif
		// #ifdef MP-WEIXIN
		uni.openLocation({
			latitude: obj.latitude, // 纬度，浮点数，范围为90 ~ -90
			longitude: obj.longitude, // 经度，浮点数，范围为180 ~ -180。
			name: obj.name, // 位置名
			address: obj.address, // 地址详情说明
			success: function() {
				console.log('success');
			}
		});
		// #endif
	}
};